﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
using Eagleshoes.PackingBarcode.Properties;

namespace Eagleshoes.PackingBarcode.Shipping
{
    public partial class DeliveryUploadForm : Form
    {
        private string currentScanedDir = Program.DeliveryScan + "\\" + DateTime.Now.ToString("yyyy-MM-dd");

        public DeliveryUploadForm()
        {
            InitializeComponent();
        }

        private void UploadButton_Click(object sender, EventArgs e)
        {
            Upload();
        }

        private void ScanDateTimePicker_ValueChanged(object sender, EventArgs e)
        {
            RefreshScanListView();
            //Focus();
        }

        private void RefreshScanListView()
        {
            currentScanedDir = Program.DeliveryScan + "\\" + ScanDateTimePicker.Value.ToString("yyyy-MM-dd");
            ScanListView.Items.Clear();
            if (Directory.Exists(currentScanedDir))
            {
                var scanedFileList = Directory.GetFiles(currentScanedDir, "*.xml");
                if (scanedFileList.Length <= 0)
                {
                    return;
                }
                foreach (var str in scanedFileList)
                {
                    ScanListView.Items.Add(new ListViewItem {Text = Path.GetFileNameWithoutExtension(str), Tag = str, ImageIndex = 0});
                }
                return;
            }

            ScanListView.Items.Add(new ListViewItem {Text = "没有数据", Tag = null, ImageIndex = 0});
        }

        private void DeliveryUploadForm_Load(object sender, EventArgs e)
        {
            RefreshScanListView();
        }

        private void Upload()
        {
            if (ScanListView.SelectedIndices.Count <= 0)
            {
                return;
            }
            var str = ScanListView.Items[ScanListView.SelectedIndices[0]].Tag as string;
            if (string.IsNullOrEmpty(str)) return;
            var doc = XElement.Load(str);
            var cartonList = (from e in doc.Elements("carton") select e.Value).ToArray();
            Program.CartonClient.SaveShippingScanedData(cartonList);
        }

       

        private void DeliveryUploadForm_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F10:
                case Keys.Escape:
                    Close();
                    break;
                case Keys.F3:
                    Upload();
                    break;
                
            }
        }

        #region Nested type: FinishedUpdate

        private delegate void FinishedUpdate(string msg);

        #endregion

       
    }
}